
package br.edu.sistemaacademico;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.CloseAction;
import javax.swing.table.DefaultTableModel;

import br.edu.sistemaacademico.Decorator.ConcretDecorator;
import br.edu.sistemaacademico.adapter.IMenuCadastro;
import br.edu.sistemaacademico.facade.DataFacade;
import br.edu.sistemaacademico.pojo.Aluno;
import br.edu.sistemaacademico.pojo.Classe;
import br.edu.sistemaacademico.pojo.Curso;
import br.edu.sistemaacademico.pojo.Disciplina;
import br.edu.sistemaacademico.pojo.Historico;
import br.edu.sistemaacademico.pojo.Matricula;
import br.edu.sistemaacademico.pojo.Professor;
import br.edu.sistemaacademico.pojo.Turma;
import br.edu.sistemaacademico.state.StateHandler;
import client.ClientCommand;

public class frmMatricula extends IMenuCadastro{
	Turma turma;
    ConcretDecorator cc = null;
    
	StateHandler stateAlterarExcuir = new StateHandler(false);
	List<Matricula> matriculas = new LinkedList<Matricula>(); 
	List<Turma> classes;
	Curso curso;
	Historico historico;
	List<Historico> historicos = new LinkedList<Historico>();
	Matricula matricula;
	Aluno aluno ;
	public List<Object> camposDisciplina = ClientCommand.getCampos("TurmaService");//new ArrayList<Object>();
    private List<Object> valoresDisciplina = new ArrayList<Object>();
	public List<Object> camposMatricula = ClientCommand.getCampos("TurmaService");//new ArrayList<Object>();
    private List<Object> valoresMatricula = new ArrayList<Object>();
    private List<Object> tamanho = new ArrayList<Object>();
    List<Turma> extra;
    List<Turma> extraMatricula = new LinkedList<Turma>();
    TabelaModelo tabMatricula;
    TabelaModelo tabDisciplina;

    public frmMatricula(Aluno aluno) {
    	this.aluno = aluno;
    	execute();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jComboBox1 = new javax.swing.JComboBox();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setName("jList1"); // NOI18N
        jScrollPane1.setViewportView(jList1);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.setName("jComboBox1"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable2.setName("jTable2"); // NOI18N
        jScrollPane3.setViewportView(jTable2);

        jTabbedPane1.addTab("Disciplinas", jScrollPane3);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane2.setViewportView(jTable1);

        jTabbedPane1.addTab("Matricula", jScrollPane2);

        jButton1.setText("Adicionar");
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setText("Cancelar");
        jButton2.setName("jButton2"); // NOI18N

        jButton3.setText("Finalizar Matricula");
        jButton3.setName("jButton3"); // NOI18N

        jTextField1.setName("jTextField1"); // NOI18N

        jButton4.setText("Buscar");
        jButton4.setName("jButton4"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, 0, 473, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 277, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton4)
                .addContainerGap(72, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))
        );

        jTabbedPane1.getAccessibleContext().setAccessibleName("Matricula");
    }// </editor-fold>//GEN-END:initComponents

    public void execute() {
         if (cc==null)
                cc = new ConcretDecorator(this);
         JPanel jpDisciplinas = new JPanel();
         tamanho.add("50");
         initComponents();
         tabDisciplina = new TabelaModelo(camposDisciplina, tamanho, jTable2);
         tabMatricula = new TabelaModelo(camposMatricula, tamanho, jTable1);
         //tabModel.busca(getTfBuscar());

         ListSelectionModel listModel = jTable2.getSelectionModel();
         listModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
         listModel.addListSelectionListener(list);
         
         jComboBox1.setModel(new DefaultComboBoxModel());
         setComboBox();
         setButtons();
         setStateAlteraExcuir();
         atualiza();
          cc.setVisible(true);
    }

    ListSelectionListener list = new ListSelectionListener() {
		
		@Override
		public void valueChanged(ListSelectionEvent e) {
			try{
				if(jTable2.getSelectedRow()>=0){
			 turma = getSelectedTurma(Long.parseLong(jTable2.getValueAt(jTable2.getSelectedRow(), 0).toString()));
			 stateAlterarExcuir.change(true);
				}
				}catch(ArrayIndexOutOfBoundsException ea){
				turma = null;
				stateAlterarExcuir.change(false);
			}
		}
	};	
	public Turma getSelectedTurma(Long codigo){
		return (Turma) ClientCommand.carregaObjeto("TurmaService", "codigo ="+codigo, "");
	}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
    
    public void atualiza(){
		((DefaultTableModel) jTable2.getModel()).setNumRows(0);
		jTable2.updateUI();
		curso = (Curso) ClientCommand.carregaObjeto("CursoService","nome='"+jComboBox1.getSelectedItem()+"'", "");
		matricula =  (Matricula) ClientCommand.carregaObjeto("MatriculaService","aluno="+aluno.getId()+" and curso="+curso.getId(), "");
		classes = (List) ClientCommand.carregar("TurmaService","a.classe in (select c.codigo from tb_classe c, tb_curso cr where c.curso = cr.codigo and cr.codigo ="+curso.getId()+" )", "");  
		//this.extra = (List)ClientCommand.carregar("TurmaService","codigo not in (select a.turma from tb_historico a, tb_matricula b where b.aluno ="+aluno.getId()+"and a.matricula=b.codigo)","");
		DataFacade entrada = new DataFacade();
		StringBuilder turmas = new StringBuilder("codigo in (");
		if(classes.size()==0)
			turmas.append("0");
		else
		for(int i =0;i<classes.size();i++){
			if(i <= classes.size()-1&&i>0)
				turmas.append(","+classes.get(i).getId());
			else
				turmas.append(classes.get(i).getId());
		}
		turmas.append(")");
		
		
		StringBuilder condicao = new StringBuilder("codigo not in(");
		if(extraMatricula.size()==0)
			condicao.append("0");
		else
		for(int i =0;i<extraMatricula.size();i++){
			if(i <= extraMatricula.size()-1&&i>0)
				condicao.append(","+extraMatricula.get(i).getId());
			else
				condicao.append(extraMatricula.get(i).getId());
		}
		condicao.append(")");
		this.extra = (List)ClientCommand.carregar("TurmaService","codigo not in (select a.turma from tb_historico a, tb_matricula b where b.aluno ="+aluno.getId()+" and a.matricula="+matricula.getId()+ " ) and "+condicao
				+" and "+turmas,"");
			for(int i = 0; i < extra.size();i++ ){
    		valoresDisciplina = new LinkedList<Object>();
    		valoresDisciplina.add(extra.get(i).getId());
    		valoresDisciplina.add(extra.get(i).getTamanho());
    		valoresDisciplina.add(extra.get(i).getPeriodo());
    		extra.get(i).setProfessor((Professor) ClientCommand.carregaObjeto("ProfessorService"," codigo ="+extra.get(i).getProfessor().getId(), ""));
			extra.get(i).setClasse((Classe) ClientCommand.carregaObjeto("ClasseService","codigo ="+extra.get(i).getClasse().getId(),""));
			extra.get(i).getClasse().setDisicplina((Disciplina) ClientCommand.carregaObjeto("DisciplinaService","codigo ="+extra.get(i).getClasse().getDisicplina().getId(),""));
    		valoresDisciplina.add(extra.get(i).getProfessor().getNome());
    		valoresDisciplina.add(extra.get(i).getClasse().getDisicplina().getNome());
    		tabDisciplina.setValores(valoresDisciplina);
    		valoresDisciplina.clear();
			}
    	//}
    }
    
    public void setButtons(){
    	ActionListener listener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(arg0.getSource().equals(jButton1)){
				extraMatricula.add(turma);
				atualizaMatricula();
				atualiza();
				}else if(arg0.getSource().equals(jButton3))
					operacao();
			}
		};
		jButton1.addActionListener(listener);
    	jButton3.addActionListener(listener);
    	jComboBox1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				curso = (Curso) ClientCommand.carregaObjeto("CursoService","nome='"+jComboBox1.getSelectedItem()+"'", "");
				atualiza();
			}
		});
    }
    public void atualizaMatricula(){
		((DefaultTableModel) jTable1.getModel()).setNumRows(0);
		jTable1.updateUI();
		DataFacade entrada = new DataFacade();   
    	for(int i = 0; i < extraMatricula.size();i++ ){
    		valoresMatricula = new LinkedList<Object>();
    		valoresMatricula.add(extraMatricula.get(i).getId());
    		valoresMatricula.add(extraMatricula.get(i).getTamanho());
    		valoresMatricula.add(extraMatricula.get(i).getPeriodo());
    		extra.get(i).setProfessor((Professor) ClientCommand.carregaObjeto("ProfessorService"," codigo ="+extraMatricula.get(i).getProfessor().getId(), ""));
			extra.get(i).setClasse((Classe) ClientCommand.carregaObjeto("ClasseService","codigo ="+extra.get(i).getClasse().getId(),""));
			extra.get(i).getClasse().setDisicplina((Disciplina) ClientCommand.carregaObjeto("DisciplinaService","codigo ="+extra.get(i).getClasse().getDisicplina().getId(),""));
    		valoresMatricula.add(extraMatricula.get(i).getProfessor().getNome());
    		valoresMatricula.add(extraMatricula.get(i).getClasse().getDisicplina().getNome());
    		tabMatricula.setValores(valoresMatricula);
    		valoresMatricula.clear();
    		valoresMatricula.removeAll(extraMatricula);
    	}
    }
    
    public void setComboBox(){
    	matriculas = (List) ClientCommand.carregar("MatriculaService","aluno ="+aluno.getId(), "");
    	for(int i = 0; i < matriculas.size();i++ ){
    		matriculas.get(i).setCurso((Curso) ClientCommand.carregaObjeto("CursoService","codigo ="+matriculas.get(i).getCurso().getId(), ""));
			jComboBox1.addItem(matriculas.get(i).getCurso().getNome());
    	}
    }
    public void setStateAlteraExcuir(){
    	stateAlterarExcuir.addComponent(jButton1);
    }
    
    public void limpaFields(){
	    }

	    
		@Override
		public void menuExemplo(JMenuItem item) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void menuFechar(JMenuItem item) {
			cc.dispose();		
		}

		@Override
		public void menuLimpa(JMenuItem item) {
			limpaFields();		
		}

		@Override
		public void menuManual(JMenuItem item) {
			// TODO Auto-generated method stub		
		}

		@Override
		public void menuMementor(JMenuItem item) {
			// TODO Auto-generated method stub		
		}

		@Override
		public void menuOperacao(JMenuItem item) {
			item.setText("Realizar Matricula");
			operacao();
		}

		@Override
		public void menuSobre(JMenuItem item) {
			// TODO Auto-generated method stub
			
		}
	  
	  public void operacao(){
		  DataFacade dataFacade = null;
			dataFacade = new DataFacade();
			historico = new Historico();
			historico.setDataIncricao(dataFacade.getString(dataFacade.getDate()));
			historico.setFaltas(0);
			historico.setMedia(0f);
			historico.setMediaTurma(0f);
			historico.setSituacao("cursando");

			curso = (Curso) ClientCommand.carregaObjeto("CursoService","nome='"+jComboBox1.getSelectedItem()+"'", "");
			historico.setMatricula((Matricula)ClientCommand.carregaObjeto("MatriculaService","aluno="+aluno.getId()+" and curso="+curso.getId(), ""));
			historico.setTurma(turma);
			if(ClientCommand.gravar("HistoricoService",historico)==true)
				JOptionPane.showMessageDialog(null, "Matricula Realizada com Sucesso");
	  }
    
}
